from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

from myapp.models import User, Goods, UserFlow
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from django_test.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from django_test.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

#导入序列化对象
from myapp.myser import UserSer, GoodsSer

# 导包
import redis

#定义地址和端口
host = '127.0.0.1'
port = 6379

#建立redis连接
r = redis.Redis(host=host,port=port)

# 导入pymongo
import pymongo

# 建立mongo的链接对象
mongo_client = pymongo.MongoClient(host='localhost', port=27017)

# 对结果集美化方法
def dictfetchall(cursor):

	#获取游标描述
	desc = cursor.description

	return [

	dict(zip( [col[0] for col in desc ] ,row))

	for row in cursor.fetchall()

	]

# 关注的商品接口
class UidFlow(View):

	def get(self,request):

		uid = request.GET.get("uid",None)

		#建立游标对象
		cursor = connection.cursor()

		#执行sql语句
		cursor.execute('select a.id, a.name from goods a left join userflow b on a.id = b.gid where b.uid = %s ' % str(uid))

		#获取结果
		result = dictfetchall(cursor)

		#返回结果 手动序列化
		return HttpResponse(json.dumps(result,ensure_ascii=False,indent=4,default=str),content_type='application/json')

# 商品取关/关注接口
class GetFlow(APIView):
	def get(self,request):
		id = request.GET.get("id",None)
		uid = request.GET.get("uid",None)
		type = request.GET.get("type",1)

		if int(type) == 1:
			# 关注
			userflow = UserFlow(gid=int(id),uid=int(uid))
			try:
				userflow.save()
				message = "关注成功"
				goods = Goods.objects.filter(id=int(id)).first()
				goods.flow = goods.flow + 1
				goods.save()
			except Exception as e:
				print(str(e))
				message = "不能重复关注"
				pass
			
		else:
			# 取关
			UserFlow.objects.filter(gid=int(id),uid=int(uid)).delete()
			message = "取关成功"
			goods = Goods.objects.filter(id=int(id)).first()
			goods.flow = goods.flow - 1
			goods.save()


		return Response({'message':message})


# 添加商品接口
class AddGoods(APIView):
    def get(self, request):
        # 接收参数
        name = request.GET.get('name', '')
        desc = request.GET.get('desc', '')
        img = request.GET.get('img', '')
        price = request.GET.get('price', '')

        # 排重
        goods = Goods.objects.filter(name=name).first()

        if goods:
            res = {}
            res['code'] = 405
            res['message'] = '该商品已存在'
            return Response(res)
            
        # 进行入库
        goods = Goods(name=name, desc=desc, img=img, price=price)
        goods.save()

        # 查询商品id
        goods = Goods.objects.filter(name=name).first()

        res = {}
        res['code'] = 200
        res['id'] = goods.id
        res['message'] = '商品添加成功'

        return Response(res)

# 商品列表页
class GoodsList(APIView):
    def get(self, request):
        # 当前页
        page = int(request.GET.get('page', 1))
        # 一页有多少个
        size = int(request.GET.get('size', 1))

        # 定义从哪开始切
        data_start = (page - 1) * size

        # 定义切到哪
        data_end = page * size

        # 查询数据
        goodslist = Goods.objects.all()[data_start: data_end]

        # 查询总数量
        count = Goods.objects.count()

        # 序列化操作
        goods_ser = GoodsSer(goodslist, many=True)

        res = {}
        res['code'] = count
        res['data'] = goods_ser.data
        return Response(res)

# 商品信息接口
class GoodInfo(APIView):
    def get(self, request):
        id = int(request.GET.get('id', 0))

        # 查询数据
        good = Goods.objects.get(id=id)

        # 序列化操作
        good_ser = GoodsSer(good)

        return Response(good_ser.data)

# 商品标签添加接口
class InsertTags(APIView):
    def get(self, request):
        id = request.GET.get('id', None)
        tags = request.GET.get('tags', None)
        tags = tags.split(',')

        # 建立数据库对象
        db = mongo_client.test
        # 建立表对象
        table = db.mytags

        # 排重操作
        # 查询
        res = table.find({'gid': str(id)}).count()

        if res > 0:
            return Response({'message': '已经存在数据'})

        else:
            # 入库操作
            table.insert({'gid': str(id), 'tags': tags})
            return Response({'message': '入库成功'})

        return Response({'message': 'test'})

# 注册接口
class Register(APIView):
    def get(self, request):
        # 接收参数
        username = request.GET.get('username', '')
        password = request.GET.get('password', '')

        # 排重
        user = User.objects.filter(username=username).first()

        if user:
            res = {}
            res['code'] = 405
            res['message'] = '该用户名已存在'
            return Response(res)

        # 入库
        user = User(username=username, password=password)
        user.save()

        res = {}
        res['code'] = 200
        res['message'] = '注册成功'
        return Response(res)

# 登录接口
class Login(APIView):
    def get(self, request):
        # 接收参数
        username = request.GET.get('username', '')
        password = request.GET.get('password', '')

        # 查询数据
        user = User.objects.filter(username=username, password=password).first()

        if user:
            res = {}
            res['code'] = 200
            res['message'] = '登录成功'
            res['username'] = user.username
            res['uid'] = user.id
            return Response(res)

        else:
            res = {}
            res['code'] = 405
            res['message'] = '用户名或密码错误'
            return Response(res)

# 定义钉钉回调
import hmac
import base64
from hashlib import sha256
import urllib

def ding_back(request):
    #获取code
    code = request.GET.get("code")

    t = time.time()

    # 时间戳
    timestamp = str((int(round(t * 1000))))
    appSecret ='fp3nkGoIhS2Mi9EdVql_nKXg6Y0-HSGp-2F_p7IAv_Quc56yhhrinpqbcQRg3RqF'

    # 构造签名
    signature = base64.b64encode(hmac.new(appSecret.encode('utf-8'),timestamp.encode('utf-8'), digestmod=sha256).digest())

    # 请求接口，换取钉钉用户名
    payload = {'tmp_auth_code':code}
    headers = {'Content-Type': 'application/json'}
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature='+urllib.parse.quote(signature.decode("utf-8"))+"&timestamp="+timestamp+"&accessKey=dingoahmelrgy51wltnjzs",data=json.dumps(payload),headers=headers)

    res_dict = json.loads(res.text)
    print(res_dict)
    # return HttpResponse(res.text)

    # 判断是否为第一次钉钉登录
    user = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()

    ding_id = ''
    user_id = ''

    if user:
        # 代表曾经用过钉钉登录
        ding_id = user.username
        user_id = user.id

    else:
        # 代表首次登录，入库
        user = User(username=str(res_dict['user_info']['nick']), password='')
        # 保存入库
        user.save()
        
        # 查询用户id
        user = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()
        ding_id = str(res_dict['user_info']['nick'])
        user_id = user.id
    # 进行跳转
    return redirect('http://localhost:8080?ding_id=' + str(ding_id) + '&uid=' + str(user_id))

# 定义七牛云存储接口
from qiniu import Auth

class QiNiu(APIView):
    def get(self, request):
        # 定义密钥
        q = Auth('gne8IIvxIQPLlv5U6PoSHWi5RKbRWObzcfPU-zse', 'SePCg8HiTpN5_ugZ9uYhN0BxWWXzMWPC0KJ5GdcD')

        # 指定上传空间
        token = q.upload_token('xing1')

        print(token)

        res = {}
        res['token'] = token

        return Response(res)

# 装饰器
def my_decorator(func):
    def wrapper(request, *args, **kwargs):

        # 获取传过来的uid
        uid = request.GET.get('uid')

        if uid == uid:
            print('是自己上传的')
        else:
            print('他人上传')

        return func(request, *args, **kwargs)

    return wrapper

# 类装饰器调用
from django.utils.decorators import method_decorator

# 用户信息
class UserInfo(APIView):
    @method_decorator(my_decorator)
    def get(self, request):
        uid = request.GET.get('uid')
         # 查询数据
        user = User.objects.get(id=int(uid))

        # 序列化对象
        user_ser = UserSer(user)

        return Response(user_ser.data)
